// pages/homework/homeworkSituation/homeworkSituation.js
import https from '../../../utils/request4.js'
import httpss from '../../../utils/request2.js'
import https7 from '../../../utils/request7.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        menuId: 1,
        listData: [],
        type: null,
        classFlag: false,
        classList: [],
        selectData: {},
        total: 0,
        jumpFlag: false,
        query: {
            pageNum: 1,
            pageSize: 10,
        },
        nextPageFlag: false,
        previousPageFlag: true,
        bindmessagebox: false,
        showBottomSheet: false,
        selectedIndex: null,
        // classList: [
        //     { gradeName: '高一', className: '001', studentCount: 40 },
        //     { gradeName: '高一', className: '002', studentCount: 38 },
        //     { gradeName: '高一', className: '003', studentCount: 35 },
        //     { gradeName: '高二', className: '001', studentCount: 42 },
        //     { gradeName: '高二', className: '002', studentCount: 39 },
        //     { gradeName: '高二', className: '003', studentCount: 37 },
        //     { gradeName: '高三', className: '004', studentCount: 41 },
        //     { gradeName: '高三', className: '001', studentCount: 36 },
        //     { gradeName: '高三', className: '002', studentCount: 33 },
        //     { gradeName: '高四', className: '003', studentCount: 40 },
        //     { gradeName: '高四', className: '004', studentCount: 38 },
        //     { gradeName: '高四', className: '005', studentCount: 37 },
        //     { gradeName: '高五', className: '001', studentCount: 39 },
        //     { gradeName: '高五', className: '002', studentCount: 36 },
        //     { gradeName: '高五', className: '003', studentCount: 34 },
        //     { gradeName: '高六', className: '004', studentCount: 38 },
        //     { gradeName: '高六', className: '005', studentCount: 35 },
        //     { gradeName: '高六', className: '001', studentCount: 33 },
        //     { gradeName: '高七', className: '002', studentCount: 40 },
        //     { gradeName: '高七', className: '001', studentCount: 37 },
        //     { gradeName: '高七', className: '001', studentCount: 35 },
        //     { gradeName: '高八', className: '001', studentCount: 39 },
        //     { gradeName: '高八', className: '001', studentCount: 36 },
        //     { gradeName: '高八', className: '001', studentCount: 34 },
        //     { gradeName: '高九', className: '001', studentCount: 38 },
        //     { gradeName: '高九', className: '001', studentCount: 35 },
        //     { gradeName: '高九', className: '001', studentCount: 33 },
        // ].map(c => ({
        //     ...c,
        //     name: `${c.gradeName}${c.className}（${c.studentCount}）`
        // })),

    },
    // 点击“查看错题”
    async handleSelectWrongQuestion(e) {
        // const item = e.currentTarget.dataset.id;
        // const type = e.currentTarget.dataset.value;
        // this.setData({

        //     selectData: item,
        //     type: type,
        //     showBottomSheet: true,
        //     selectedIndex: null
        // });
        if (e.currentTarget.dataset.value == 3) {
            let item = e.currentTarget.dataset.id
            if (!this.data.jumpFlag) {
                wx.navigateTo({
                    url: `/pages/homework/bonusPoints/bonusPoints?examCourseId=${item.examCourses[0].id}`,
                });
            } else {
                wx.redirectTo({
                    url: `/pages/homework/bonusPoints/bonusPoints?examCourseId=${item.examCourses[0].id}`,
                });
            }
            return false
        } else if (e.currentTarget.dataset.value == 4) {
            // 补录答案
            let item = e.currentTarget.dataset.id
            if (!this.data.jumpFlag) {
                wx.navigateTo({
                    url: `/pages/homework/supplementAnswer/supplementAnswer?examCourseId=${item.cardId}`,
                });
            } else {
                wx.redirectTo({
                    url: `/pages/homework/supplementAnswer/supplementAnswer?examCourseId=${item.cardId}`,
                });
            }
            return false
        }
        let data = {
            examId: e.currentTarget.dataset.id.id
        }
        this.setData({
            selectData: e.currentTarget.dataset.id
        })
        let options = {
            url: '/work/class',
            method: 'get',
            data: data,
            header: { "content-type": "application/json;charset=UTF-8" }
        }
        let res = await https(options)
        if (res && res.data.code == 200) {
            const list = res.data.data;
            if (!list || list.length === 0) {
                wx.showToast({
                    title: '当前没有班级',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            if (list.length === 1) {
                const selectedClass = {
                    ...list[0],
                    name: `${list[0].gradeName}${list[0].className}（${list[0].studentCount}）`
                };
                this.setData({
                    classList: [selectedClass],
                    selectedIndex: 0,
                    selectData: e.currentTarget.dataset.id,
                    type: e.currentTarget.dataset.value
                });
                this.confirmSelect();
                return;
            }
            this.setData({
                classList: list.map(item => ({
                    ...item,
                    name: `${item.gradeName}${item.className}（${item.studentCount}）`
                })),
                type: e.currentTarget.dataset.value,
                showBottomSheet: true
            });
        }

    },

    handleSelect(e) {
        const index = e.currentTarget.dataset.index;
        this.setData({ selectedIndex: index });
    },


    // 点击确定
    async confirmSelect() {
        // console.log("调用了");

        const index = this.data.selectedIndex;
        console.log('selectedIndex:', index);

        if (index === null) {
            wx.showToast({ title: '请先选择班级', icon: 'none' });
            return;
        }
        const selectedClass = this.data.classList[index];
        const item = this.data.selectData;
        const type = this.data.type;
        // console.log(selectedClass);
        // console.log(item);
        // console.log(type);

        this.selectClassS(selectedClass, item, type);

        this.setData({ showBottomSheet: false });
    },

    // 点击取消
    cancelSelect() {
        this.setData({ showBottomSheet: false });
    },
    bindphone() {
        console.log("点击了");

        wx.navigateTo({
            url: '/pages/homework/bindTeacherInfo/bindTeacherInfo',
        })
    },
    emptybindphone() {
        this.setData({
            bindmessagebox: false
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.hideTabBar({ animation: false });
        this.setData({
            previousPageFlag: true
        })
        if (options.flag == 1) {
            this.setData({
                menuId: 2,
                listData: [],
                jumpFlag: true
            })
            this.getWorklist()
        } else if (options.flag == 2) {
            this.setData({
                menuId: 3,
                listData: [],
                jumpFlag: true
            })
            this.supplementaryAnswerList()
        } else {
            this.getInfo()
        }
    },
    async getInfo() {
        let data = {
            page: this.data.query.pageNum,
            pageSize: this.data.query.pageSize,
            query: {
                classId: 0,
                courseId: 0,
                gradeId: 0,
                name: ''
            }
        }
        let that = this
        let options = {
            url: '/work/list',
            method: 'post',
            data: data,
            header: { "content-type": "application/json;charset=UTF-8" }
        }
        let res = await https(options)
        if (res && res.data.code == 200) {
            res.data.data.items.map(ress => {
                ress.startTime = ress.startTime.substring(0, 10)
            })
            this.setData({
                listData: res.data.data.items,
                total: Math.ceil(res.data.data.total / this.data.query.pageSize)
            })
            if (this.data.total == this.data.query.pageNum) {
                // 下一页禁用
                this.setData({
                    nextPageFlag: true
                })
            } else {
                this.setData({
                    nextPageFlag: false
                })
            }
            if (this.data.query.pageNum == 1) {
                // 上一页禁用
                this.setData({
                    previousPageFlag: true
                })
            } else {
                this.setData({
                    previousPageFlag: false
                })
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
    },
    selectMenu(e) {
        this.setData({
            menuId: e.currentTarget.dataset.value,
            listData: [],
            query: {
                pageNum: 1,
                pageSize: 10,
            },
            total: 0,
            nextPageFlag: false,
            previousPageFlag: true
        })
        if (e.currentTarget.dataset.value == 2) {
            this.getWorklist()
        } else if (e.currentTarget.dataset.value == 1) {
            this.getInfo()
        } else if (e.currentTarget.dataset.value == 3) {
            // 补充答案
            this.supplementaryAnswerList()
        }
    },
    nextPage() {
        this.setData({
            query: {
                pageNum: this.data.query.pageNum + 1,
                pageSize: 10
            }
        })
        if (this.data.total == this.data.query.pageNum) {
            // 下一页禁用
            this.setData({
                nextPageFlag: true
            })
        } else {
            this.setData({
                nextPageFlag: false
            })
        }
        if (this.data.query.pageNum == 1) {
            // 上一页禁用
            this.setData({
                previousPageFlag: true
            })
        } else {
            this.setData({
                previousPageFlag: false
            })
        }
        if (this.data.menuId == 1) {
            this.getInfo()
        } else if (this.data.menuId == 2) {
            this.getWorklist()
        } else if (this.data.menuId == 3) {
            this.supplementaryAnswerList()
        }
    },
    previousPage() {
        this.setData({
            query: {
                pageNum: this.data.query.pageNum - 1,
                pageSize: 10
            }
        })
        if (this.data.total == this.data.query.pageNum) {
            // 下一页禁用
            this.setData({
                nextPageFlag: true
            })
        } else {
            this.setData({
                nextPageFlag: false
            })
        }
        if (this.data.query.pageNum == 1) {
            // 上一页禁用
            this.setData({
                previousPageFlag: true
            })
        } else {
            this.setData({
                previousPageFlag: false
            })
        }
        if (this.data.menuId == 1) {
            this.getInfo()
        } else if (this.data.menuId == 2) {
            this.getWorklist()
        } else if (this.data.menuId == 3) {
            this.supplementaryAnswerList()
        }
    },
    // bindPickerChange(e) {
    //     console.log(e.detail.value, '----------------');
    // },
    cancel() {
        this.setData({
            classFlag: false
        })
    },
    async supplementaryAnswerList() {
        let data = {
            pageNum: this.data.query.pageNum,
            pageSize: this.data.query.pageSize
        }
        let options = {
            url: `/system/card/answer/record/list`,
            method: 'get',
            data,
            header: { "content-type": "application/json;charset=UTF-8" }
        }
        let res = await https7(options)
        if (res && res.data.code == 200) {
            res.data.rows.map(ress => {
                ress.updateTime = ress.updateTime.substring(0, 10)
            })
            this.setData({
                listData: res.data.rows,
                total: Math.ceil(res.data.total / this.data.query.pageSize)
            })
            if (this.data.total == this.data.query.pageNum) {
                // 下一页禁用
                this.setData({
                    nextPageFlag: true
                })
            } else {
                this.setData({
                    nextPageFlag: false
                })
            }
            if (this.data.query.pageNum == 1) {
                // 上一页禁用
                this.setData({
                    previousPageFlag: true
                })
            } else {
                this.setData({
                    previousPageFlag: false
                })
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
    },
    async getWorklist() {
        // 获取答题卡打分异常作业
        let data = {
            page: this.data.query.pageNum,
            pageSize: this.data.query.pageSize
        }
        let options = {
            url: '/scoreexception/worklist',
            method: 'post',
            data: data,
            header: { "content-type": "application/json;charset=UTF-8" }
        }
        let res = await https(options)
        if (res && res.data.code == 200) {
            res.data.data.items.map(ress => {
                ress.startTime = ress.startTime.substring(0, 10)
            })
            this.setData({
                listData: res.data.data.items,
                total: Math.ceil(res.data.data.total / this.data.query.pageSize)
            })
            if (this.data.total == this.data.query.pageNum) {
                // 下一页禁用
                this.setData({
                    nextPageFlag: true
                })
            } else {
                this.setData({
                    nextPageFlag: false
                })
            }
            if (this.data.query.pageNum == 1) {
                // 上一页禁用
                this.setData({
                    previousPageFlag: true
                })
            } else {
                this.setData({
                    previousPageFlag: false
                })
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
    },
    scanTheCode() {
        wx.scanCode({
            success: (res) => {
                console.log(res.result, '---------------');
                if (!this.data.jumpFlag) {
                    wx.navigateTo({
                        url: `/pages/homework/supplementAnswer/supplementAnswer?examCourseId=${res.result}`,
                    });
                } else {
                    wx.redirectTo({
                        url: `/pages/homework/supplementAnswer/supplementAnswer?examCourseId=${res.result}`,
                    });
                }
            },
            fail: (err) => {
                if (err.errMsg.includes('auth deny')) {
                    wx.showModal({
                        title: '提示',
                        content: '需要相机权限，请前往设置开启',
                        success: (res) => {
                            if (res.confirm) wx.openSetting() // 跳转权限设置页
                        }
                    })
                }
            }
        })
    },
    async jumpPage(e) {
        if (e.currentTarget.dataset.value == 3) {
            let item = e.currentTarget.dataset.id
            if (!this.data.jumpFlag) {
                wx.navigateTo({
                    url: `/pages/homework/bonusPoints/bonusPoints?examCourseId=${item.examCourses[0].id}`,
                });
            } else {
                wx.redirectTo({
                    url: `/pages/homework/bonusPoints/bonusPoints?examCourseId=${item.examCourses[0].id}`,
                });
            }
            return false
        } else if (e.currentTarget.dataset.value == 4) {
            // 补录答案
            let item = e.currentTarget.dataset.id
            if (!this.data.jumpFlag) {
                wx.navigateTo({
                    url: `/pages/homework/supplementAnswer/supplementAnswer?examCourseId=${item.cardId}`,
                });
            } else {
                wx.redirectTo({
                    url: `/pages/homework/supplementAnswer/supplementAnswer?examCourseId=${item.cardId}`,
                });
            }
            return false
        }
        let data = {
            examId: e.currentTarget.dataset.id.id
        }
        this.setData({
            selectData: e.currentTarget.dataset.id
        })
        let options = {
            url: '/work/class',
            method: 'get',
            data: data,
            header: { "content-type": "application/json;charset=UTF-8" }
        }
        let res = await https(options)
        if (res && res.data.code == 200) {
            const list = res.data.data;
            if (!list || list.length === 0) {
                wx.showToast({
                    title: '当前没有班级',
                    icon: 'none',
                    duration: 2000
                });
                return;
            }
            if (list.length === 1) {
                const selectedClass = {
                    ...list[0],
                    name: `${list[0].gradeName}${list[0].className}（${list[0].studentCount}）`
                };
                this.setData({
                    classList: [selectedClass],
                    selectedIndex: 0,
                    selectData: e.currentTarget.dataset.id,
                    type: e.currentTarget.dataset.value
                });
                this.confirmSelect();
                return;
            }
            this.setData({
                classList: list.map(item => ({
                    ...item,
                    name: `${item.gradeName}${item.className}（${item.studentCount}）`
                })),
                type: e.currentTarget.dataset.value,
                showBottomSheet: true
            });
        }

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        try {


            let phoneNumber = wx.getStorageSync('username')
            let phoneStr = String(phoneNumber);
            let res = await httpss({
                url: '/open/system/getTeacherByNumber',
                method: 'get',
                data: { phone: phoneStr },
                header: { "content-type": "application/json;charset=UTF-8" }
            })

            if (res && res.data.code == 200) {
                if (res.data.data.openId == null || res.data.data.openId === '') {
                    let teacherUserInfo = res.data.data
                    wx.setStorageSync('teacherUserInfo', teacherUserInfo);
                    // this.setData({ bindmessagebox: true });
                    const hasShown = wx.getStorageSync('hasShownBindPrompt');
                    if (!hasShown) {
                        this.setData({ bindmessagebox: true });
                        wx.setStorageSync('hasShownBindPrompt', true);
                    }
                } else {
                    let teacherUserInfo = res.data.data
                    wx.setStorageSync('teacherUserInfo', teacherUserInfo);
                    this.setData({ bindmessagebox: false });
                    // wx.showTabBar({ animation: true });
                }
            } else {
                wx.showModal({
                    title: '提示',
                    content: '登录状态失效，请重新登录',
                    showCancel: false,
                    success: () => {
                        wx.reLaunch({ url: '/pages/homework/login/login' });
                    }
                });
            }
        } catch (e) {
            console.error('onShow error:', e)
        }
        wx.hideTabBar({ animation: false });
        if (this.getTabBar && this.getTabBar()) {
            this.getTabBar().refreshTabBar();
        }
    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    async selectClass(e) {
        let item = e.currentTarget.dataset.item
        let options = {
            url: `/work/pushstate?examCourseId=${this.data.selectData.examCourses[0].id}`,
            method: 'get',
            header: { "content-type": "application/json;charset=UTF-8" }
        }
        let res = await https(options)
        if (res && res.data.code == 200) {
            if (res.data.data != 3) {
                let apioptions = {
                    url: `/score/publishscore`,
                    method: 'post',
                    data: { courseId: this.data.selectData.examCourses[0].id },
                    header: { "content-type": "application/x-www-form-urlencoded" }
                }
                let ress = await https(apioptions)
                if (ress && ress.data.code == 200) {
                    if (this.data.type == 1) {
                        wx.navigateTo({
                            url: `/pages/homework/wrongQuestion/wrongQuestion?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                        });
                    } else if (this.data.type == 2) {
                        wx.navigateTo({
                            url: `/pages/homework/homeworkDetails/homeworkDetails?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                        });
                    } else if (this.data.type == 3) {
                        wx.navigateTo({
                            url: `/pages/homework/bonusPoints/bonusPoints?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                        });
                    }
                } else {
                    wx.showToast({
                        title: ress.data.message,
                        icon: 'none',
                        duration: 2000 //持续的时间
                    })
                }
            } else {
                if (this.data.type == 1) {
                    wx.navigateTo({
                        url: `/pages/homework/wrongQuestion/wrongQuestion?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                    });
                } else if (this.data.type == 2) {
                    wx.navigateTo({
                        url: `/pages/homework/homeworkDetails/homeworkDetails?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                    });
                } else if (this.data.type == 3) {
                    wx.navigateTo({
                        url: `/pages/homework/bonusPoints/bonusPoints?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                    });
                }
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
        this.setData({
            classFlag: false
        })
    },
    async selectClassS(e) {
        let item = e
        let options = {
            url: `/work/pushstate?examCourseId=${this.data.selectData.examCourses[0].id}`,
            method: 'get',
            header: { "content-type": "application/json;charset=UTF-8" }
        }
        let res = await https(options)
        if (res && res.data.code == 200) {
            if (res.data.data != 3) {
                let apioptions = {
                    url: `/score/publishscore`,
                    method: 'post',
                    data: { courseId: this.data.selectData.examCourses[0].id },
                    header: { "content-type": "application/x-www-form-urlencoded" }
                }
                let ress = await https(apioptions)
                if (ress && ress.data.code == 200) {
                    if (this.data.type == 1) {
                        wx.navigateTo({
                            url: `/pages/homework/wrongQuestion/wrongQuestion?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                        });
                    } else if (this.data.type == 2) {
                        wx.navigateTo({
                            url: `/pages/homework/homeworkDetails/homeworkDetails?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                        });
                    } else if (this.data.type == 3) {
                        wx.navigateTo({
                            url: `/pages/homework/bonusPoints/bonusPoints?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                        });
                    }
                } else {
                    wx.showToast({
                        title: ress.data.message,
                        icon: 'none',
                        duration: 2000 //持续的时间
                    })
                }
            } else {
                if (this.data.type == 1) {
                    wx.navigateTo({
                        url: `/pages/homework/wrongQuestion/wrongQuestion?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                    });
                } else if (this.data.type == 2) {
                    // wx.navigateTo({
                    //     url: `/pages/homework/homeworkDetails/homeworkDetails?examId=${this.data.selectData.id}&title=${this.data.selectData.name}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}`,
                    // });
                    wx.navigateTo({
                        url: `/pages/homework/homeworkDetails/homeworkDetails?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                    });
                } else if (this.data.type == 3) {
                    wx.navigateTo({
                        url: `/pages/homework/bonusPoints/bonusPoints?examId=${this.data.selectData.id}&gradeid=${item.gradeId}&courseid=${this.data.selectData.examCourses[0].id}&classId=${item.classId}&title=${this.data.selectData.name}`,
                    });
                }
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
        this.setData({
            showBottomSheet: false
        })
    }
})

